package com.czy;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 主题的消费
 *
 */
public class TestTopicConsumer {

	private static String brokerURL="tcp://127.0.0.1:61616";
	private static String topicName="topic-hello";
	
	public static void main(String[] args) throws Exception {

		ActiveMQConnectionFactory factory=new ActiveMQConnectionFactory(brokerURL);
		Connection connection = factory.createConnection();
		connection.start();
		
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Topic topic = session.createTopic(topicName);
		
		MessageConsumer consumer = session.createConsumer(topic);
		System.out.println("1号消费者");
		consumer.setMessageListener(new MessageListener() {
			
			@Override
			public void onMessage(Message message) {
				if(message instanceof TextMessage) {
					TextMessage textMessage=(TextMessage) message;
					try {
						System.out.println("接收到消息:"+textMessage.getText());
					} catch (JMSException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		System.in.read();
		session.close();
		connection.close();
		System.out.println("主题消费发送完成");
		
	}

}
